﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace FFSupplier.Common.Helper
{
    /// <summary>
    /// WEB 请求帮助类
    /// by DZL 20190505
    /// </summary>
    public class WebAPIHelper
    {
        #region 同步请求
        static CookieContainer cookie = new CookieContainer();
        /// <summary>
        /// 同步Post
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns>返回json格式</returns>
        public static string HttpPost(string Url, IDictionary<string, string> Params)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType = "application/json";
                request.CookieContainer = cookie;

                //发送POST数据  
                StringBuilder bufferParams = new StringBuilder();
                if (!(Params == null || Params.Count == 0))
                {
                    int i = 0;
                    foreach (string key in Params.Keys)
                    {
                        if (i > 0)
                        {
                            bufferParams.AppendFormat("&{0}={1}", key, Params[key]);
                        }
                        else
                        {
                            bufferParams.AppendFormat("{0}={1}", key, Params[key]);
                            i++;
                        }
                    }
                }
                request.ContentLength = Encoding.UTF8.GetByteCount(bufferParams.ToString());

                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(bufferParams);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            
        }

        public static string Post(string url, object p, string v)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 同步Post请求 方式二
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postData">json格式的数据</param>
        /// <returns></returns>
        public static string HttpPost2(string Url, string postData)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/json";
                request.CookieContainer = cookie;

                //发送POST数据  
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = byteArray.Length;

                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(byteArray, 0, byteArray.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }


        }

        /// <summary>
        /// 同步Get
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns>返回json格式</returns>
        public static string HttpGet(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            //request.ContentType = "text/html;charset=UTF-8";
            request.ContentType = "application/json";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        #endregion 同步请求


        public static string Post(string strURL, string paraUrlCoded, string ContentType)
        {
            string ret = "";
            try
            {
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = ContentType;
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请 求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;
                // 获得响应流
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = myreader.ReadToEnd();
                myreader.Close();
            }
            catch (Exception e)
            {

                throw e;
            }


            return ret;
        }

    }
}
